package org.vectrics.cms;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.vectrics.SystemException;
import org.vectrics.domain.Domain;
import org.vectrics.hibernate.Filter;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.provider.CoreServiceLocator;

public class ContentHelper {
	private Logger log = Logger.getLogger(ContentHelper.class);
	

	public String getContentFileName(Domain domain, String section, String code) {
		if (domain == null) {
			domain = CoreServiceLocator.getSystemService().findDomain(1l);
		}
		String contentDirectory = CoreServiceLocator.getConfiguration()
			.getDynamicContentPath(domain);
		String contentFile = contentDirectory + "/" + section + "/" + code;
		return(contentFile);
	}
	
	public String getContent(Domain domain, String section, String code) {
		StringBuffer content = new StringBuffer();
		String contentFile = this.getContentFileName(domain, section, code);
		try {
			URL url = null;
			URLConnection urlConnection = null;
			try {
				url = new URL(contentFile);
				urlConnection = url.openConnection();
			} catch (MalformedURLException ex) {
				log.error("Mal Formada la URL: " + contentFile, ex);
				throw new SystemException("Mal Formada la URL: " + contentFile, ex);
			} catch (IOException ex) {
				log.error("Exception opening URL: " + contentFile, ex);
				throw new SystemException("Exception opening file: " + contentFile, ex);
			}
			InputStream inputStream = urlConnection.getInputStream();
			boolean done = false;
			while (!done) {
				int r = inputStream.read();
				if (r < 0) {
					done = true;
				} else {
					content.append((char)r);
				}
			}
		} catch (Exception ex) {
			log.error("Exception getting content from file: " + contentFile, ex);
			//content.append("Error finding content: " + contentFile);
			try {
				log.info("Content file did not exist - creating empty file for now");
				FileOutputStream file = new FileOutputStream(contentFile);

				file.close();
			} catch (Exception ex2) {
				throw new SystemException("Exception creating file (after CMS file not found)", ex2);
			}
		}
		return content.toString();
	}

	
	public void saveContent(Domain domain, String section, String code, String content) {
		String fileName = CoreServiceLocator.getConfiguration().getDynamicContentPath(domain) + "/"
		    + section + "/" + code;
		FileOutputStream file = null;
		try {
			file = new FileOutputStream(fileName);
			file.write(content.getBytes());
		} catch (Exception ex) {
			throw new SystemException("Exception writing content");
		} finally {
			if (file != null) {
				try {
					file.close();
				} catch (Exception cex) {
					throw new SystemException("Exception closing file", cex);
				}
			}
		}
	}
	
	
	
	public CmsSection findCmsSection(Domain domain, String sectionCode) {
		Filter filter = new Filter();
		filter.addSelectField("cmsSection");
		filter.addFrom("CmsSection", "cmsSection");
		filter.addParameterCondition("cmsSection.domain.id", "=", domain.getId());
		filter.addParameterCondition("cmsSection.code", "=", sectionCode);

		List elements = filter.createQuery(ThreadProperties.getSession()).list();
		if (elements.size() == 0)
			throw new SystemException("Could not find CMS Section for domain=" 
					+ domain + "  section="
					+ sectionCode);
		CmsSection section = (CmsSection)elements.iterator().next();
		return(section);
	}

	
	
	/**
	 * Returns all CMS Sections for the data owner.
	 * @param domain The data owner.
	 * @return
	 */
	public Iterator findAllCmsSections(Domain domain) {
		Filter filter = new Filter();
		filter.addSelectField("cmsSection");
		filter.addFrom("CmsSection", "cmsSection");
		filter.addParameterCondition("cmsSection.domain.id", "=", domain.getId());
		filter.addOrderBy("cmsSection.code");
		
		Iterator list = filter.createQuery(ThreadProperties.getSession()).iterate();
		return(list);
	}
	
}
